from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from django.conf import settings

from . import serializers
from .utils import generate_sign_openid
from .models import OAuthQQUser


class OAuthQQLoginView(APIView):
    def get(self,request):
        state = request.query_params.get("state",'/')

        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state=state)

        login_url = oauth_qq.get_qq_url()

        return Response(data={"auth_url":login_url})

class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer
    def get(self,request):
        code = request.query_params.get('code')

        if not code:
            return Response('code丢失了')

        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')


        access_token = oauth_qq.get_access_token(code)

        openid = oauth_qq.get_open_id(access_token)
        print(openid)
        # return Response('openid = %s' % openid )

        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            sign_openid = generate_sign_openid(openid)
            return Response({"access_token" : sign_openid})

        else:
            user = oauth_qq_user.user

            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

        return Response({
                "token": token,
                "username": user.username,
                "user_id": user.id
            })

    def post(self,request):

        dict_data = request.data

        serializer = self.get_serializer(data = dict_data)

        serializer.is_valid(raise_exception = True)

        user = serializer.save()

        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return  Response({
            "token" : token,
            "user_id":user.id,
            "username": user.username
        })


